/* 员工信息列表页面 */
<template>
  <!-- 主体div -->
  <el-card>
    <div class="main">
      <!-- 上半部分主体div -->
      <div
        class="container"
        style="box-shadow: 10px 10px 5px rgba(99, 99, 153, 0.2)"
      >
        <!-- 搜索表单区域 -->
        <el-form
          :inline="true"
          :model="fromData"
          class="demo-form-inline"
          ref="searchFormRef"
        >
          <!-- 表单项 prop的值要和input对象绑定的值一致 -->
          <el-form-item label="员工名称：" prop="name">
            <el-input
              v-model="fromData.name"
              placeholder="请输入员工名称"
              @clear="searchEmployee"
              clearable
            >
            </el-input>
          </el-form-item>
          <el-form-item label="所属部门：" prop="department">
            <!-- 选择菜单 -->
            <el-select
              v-model="employeeList.department"
              placeholder="请选择部门信息"
            >
              <el-option label="运营部" value="运营部"></el-option>
              <el-option label="技术部" value="技术部"></el-option>
              <el-option label="CEO" value="CEO"></el-option>
              <el-option label="高管" value="高管"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="学历：" prop="degree">
            <el-select v-model="employeeList.degree" placeholder="请选择学历">
              <el-option label="本科" value="本科"></el-option>
              <el-option label="研究生" value="研究生"></el-option>
              <el-option label="博士" value="博士"></el-option>
            </el-select>
          </el-form-item>
          <!-- 设置两个功能栏，分别是搜索和重置功能 -->
          <el-form-item>
            <el-button
              type="primary"
              icon="el-icon-search"
              size="mini"
              @click="searchEmployee"
              >搜索</el-button
            >
          </el-form-item>
          <!-- 实现对表单输入的数据进行重置 -->
          <el-form-item>
            <el-button
              type="info"
              icon="el-icon-refresh-left"
              size="mini"
              plain
              @click="resetserchForm"
              >重置
            </el-button>
          </el-form-item>

          <!-- 表单下方四个按钮控件，添加到div布局中，设置布局大小，边框 -->
          <div class="btn_form">
            <el-form-item class="btn">
              <el-button
                type="primary"
                icon="el-icon-plus"
                size="mini"
                plain
                @click="addDialogVisible = true"
                >添加</el-button
              >
            </el-form-item>
            <el-form-item>
              <el-button
                type="success"
                icon="el-icon-edit"
                size="mini"
                plain
                disabled
                >修改</el-button
              >
            </el-form-item>
            <el-form-item>
              <el-button
                type="danger"
                icon="el-icon-delete"
                size="mini"
                plain
                disabled
                >删除</el-button
              >
            </el-form-item>

            <el-form-item>
              <el-button
                type="warning"
                icon="el-icon-download"
                size="mini"
                plain
                >导出</el-button
              >
            </el-form-item>
          </div>
        </el-form>
      </div>

      <!-- 员工列表 ,border为边框，stripe隔行变色,显示员工信息 -->
      <el-table
        :data="employeeList"
        border
        style="
          font-size: 14px;
          width: 100%;
          box-shadow: 10px 10px 5px rgba(99, 99, 153, 0.2);
        "
        :header-cell-style="{ background: '#f8f8f9', color: '#515a6e' }"
      >
        <!-- 给table表头设置背景颜色  backgorud:背景颜色 color：字体颜色-->
        <el-table-column type="selection" width="40" align="center">
        </el-table-column
        ><!-- 在首列添加可选择的按钮 -->
        <el-table-column
          type="index"
          label="工号"
          align="center"
          width="50%"
        ></el-table-column>

        <el-table-column
          label="员工"
          prop="name"
          min-width="10%"
          align="center"
        ></el-table-column>
        <el-table-column
          label="性别"
          prop="sex"
          min-width="10%"
          align="center"
        ></el-table-column>
        <el-table-column
          label="年龄"
          prop="age"
          min-width="10%"
          align="center"
        ></el-table-column>
        <el-table-column
          label="生日"
          prop="birthday"
          min-width="10%"
          align="center"
          :formatter="dateFormat"
        >
        </el-table-column>
        <el-table-column
          label="部门"
          prop="department"
          min-width="10%"
          align="center"
        ></el-table-column>
        <el-table-column
          label="员工状态"
          prop="state"
          min-width="10%"
          align="center"
        >
          <!-- tag标签，采用嵌套三元表达式的方法，判断员工的状态，动态显示颜色 -->
          <template slot-scope="scope">
            <!-- 若状态为‘在职’，则显示success， 若不是则执行后面的嵌套层 -->
            <el-tag
              effect="light"
              :type="
                scope.row.state == '在职'
                  ? 'success'
                  : scope.row.state == '实习'
                  ? 'primary'
                  : 'danger'
              "
            >
              {{ scope.row.state }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column
          label="学历"
          prop="degree"
          min-width="10%"
          align="center"
        >
        </el-table-column>

        <el-table-column label="操作" min-width="10%" align="center">
          <template slot-scope="scope">
            <!-- 修改员工信息方法 参数为：row行数的id -->
            <el-tooltip
              effect="dark"
              content="修改信息"
              placement="top-start"
              :enterable="false"
            >
              <!--文字提示 enterable 隐藏-->
              <el-button
                type="primary"
                icon="el-icon-edit"
                size="mini"
                @click="showEditDialog(scope.row.id)"
              >
              </el-button>
            </el-tooltip>

            <!-- 后期需要修改一下，将按钮disabled，演示模式下不能进行删除操作 -->
            <el-tooltip
              effect="dark"
              content="删除员工"
              placement="top-start"
              :enterable="false"
            >
              <!--文字提示 enterable 隐藏-->
              <!-- 删除员工信息方法 参数为行数row行数id，row行数 -->
              <el-button
                type="danger"
                icon="el-icon-delete"
                size="mini"
                @click="handleDelete(scope.row.id, scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
        <!-- 索引列 -->
      </el-table>

      <!-- 分页组件 size-change:每页最大变化 current-change：当前页数变化 layout：功能组件 
    之前不能实现切换的bug改好~！-->
      <div
        class="block"
        style="
          text-align: center;
          margin-top: 15px;
          margin-left: 10px;
          padding: 10px 10px;
        "
      >
        <div>
          <el-pagination
            background
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="fromData.pageIndex"
            :page-sizes="pageInfo.pageSizes"
            :page-size="fromData.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="pageInfo.total"
          >
            <!-- @size-change：每页显示条数个数点击事件，当切换时动态的切换每页显示的条数
               @current-change：当前页数点击事件
               current-page:当前页码，默认为第一页
               page-sizes：在页面可选择的页码数[1,10,20,50] 
               page-size：每页显示的条数，可以动态的修改
               total：显示的是从后端获得数据的总数  -->
          </el-pagination>
        </div>
      </div>

      <!-- 新增员工区域 -->
      <el-dialog
        center
        title="添加员工"
        :visible.sync="addDialogVisible"
        width="50%"
        @close="addDialogClosed"
      >
        <!-- model:双向绑定模型， rules:绑定添加员工的规则 -->

        <el-form
          size="medium "
          :model="addEmployeeInfo"
          :rules="AddFormRules"
          ref="addFormRef"
          :inline="true"
          label-width="80px"
        >
          <!-- 用户名 -->

          <el-form-item label="姓名" prop="name">
            <el-input v-model="addEmployeeInfo.name"></el-input>
          </el-form-item>
          <!-- 密码 -->

          <el-form-item
            label="年龄"
            prop="age"
            :inline="true"
            style="float: right"
          >
            <el-input v-model="addEmployeeInfo.age"></el-input>
          </el-form-item>

          <el-form-item label="薪水" prop="degree">
            <el-input v-model="addEmployeeInfo.salary"></el-input>
          </el-form-item>

          <el-form-item label="性别" prop="sex" style="float: right">
            <el-select v-model="addEmployeeInfo.sex">
              <el-option
                v-for="item in addEmployeeSexOptions"
                :label="item.sex"
                :key="item.gender"
                :value="item.sex"
              ></el-option>
            </el-select>
          </el-form-item>

          <!-- 邮箱 -->
          <el-form-item label="身份" prop="state">
            <el-select v-model="addEmployeeInfo.state">
              <el-option
                v-for="item in addEmployeeStateOptions"
                :label="item.state"
                :key="item.stateName"
                :value="item.state"
              ></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="生日" prop="birthday" style="float: right">
            <el-date-picker
              v-model="addEmployeeInfo.birthday"
              type="date"
              placeholder="选择日期"
              value-format="yyyy-MM-dd"
            >
            </el-date-picker>
          </el-form-item>

          <el-form-item label="部门" prop="department">
            <el-select v-model="addEmployeeInfo.department">
              <el-option
                :label="item.dept"
                v-for="item in addEmployeeDepartOptions"
                :key="item.deptName"
                :value="item.dept"
              ></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="学历" prop="degree" style="float: right">
            <el-select v-model="addEmployeeInfo.degree">
              <el-option
                :label="item.degree"
                v-for="item in addEmployeeDegreeOptions"
                :key="item.degreeName"
                :value="item.degree"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>

        <!-- 内容底部区域，两个按钮区域-->
        <span slot="footer" class="dialog-footer">
          <el-button @click="addDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="doAddEmployee">确定</el-button>
        </span>
      </el-dialog>

      <!-- 修改员工信息对话框区域 -->
      <el-dialog
        center
        title="修改员工信息"
        :visible.sync="editDialogVisible"
        width="50%"
        @close="editDialogClosed"
      >
        <el-form
          :model="editForm"
          :rules="editFormRules"
          ref="editFormRef"
          label-width="70px"
        >
          <!-- 用户名 -->
          <el-form-item label="员工" prop="name">
            <el-input v-model="editForm.name" disabled></el-input>
          </el-form-item>
          <!-- 密码 -->
          <el-form-item label="年龄" prop="age">
            <el-input v-model="editForm.age"></el-input>
          </el-form-item>
          <!-- 密码 -->
          <el-form-item label="性别" prop="sex">
            <el-input v-model="editForm.sex"></el-input>
          </el-form-item>
          <!-- 邮箱 -->
          <el-form-item label="职位" prop="state">
            <el-input v-model="editForm.state" disabled></el-input>
          </el-form-item>
          <!-- 用户名 -->
          <el-form-item label="生日" prop="birthday">
            <el-input v-model="editForm.birthday"></el-input>
          </el-form-item>
          <!-- 用户名 -->
          <el-form-item label="部门" prop="department">
            <el-input v-model="editForm.department" disabled></el-input>
          </el-form-item>
          <!-- 用户名 -->
          <el-form-item label="学历" prop="degree">
            <el-input v-model="editForm.degree"></el-input>
          </el-form-item>
          <!-- 用户名 -->
          <el-form-item label="薪水" prop="salary" disabled>
            <el-input v-model="editForm.salary" disabled></el-input>
          </el-form-item>
        </el-form>

        <!-- 内容底部区域，两个按钮区域-->
        <span slot="footer" class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="doModifyEmployee">确定</el-button>
        </span>
      </el-dialog>
    </div>
  </el-card>
</template>

<script>
import {
  validateUsername,
  validateAge,
  validatGender,
  validateDepartment,
  validateBirthday,
  validateState,
  validateSalary,
  validateDegree,
} from "../../../components/common/validate";

import { list, recycle, del } from "../../../api/employee/index";
export default {
  //created()方法指的是在页面开启的同时就调用里面的方法。
  created() {
    this.queryEmpList(); //获取当前员工列表
    //定义数据加载中的动画
    const loading = this.$loading({
      lock: true, //全屏锁定
      text: "数据加载中......", //输出的文本信息
      spinner: "el-icon-loading",
      background: "rgba(0, 0, 0, 0.7)",
    });
    setTimeout(() => {
      loading.close();
    }, 1000); /* 设置时间为1秒 */
  },
  //数据定义,判断输入的数据是否为空
  data() {
    return {
      value1: "",
      value2: "",
      employeeList: [], //用户列表
      //定义ref对象
      formInline: {
        region: "",
        name: "",
        sex: "",
        degree: "",
      },
      //日期选择器格式
      pickerOptions: {
        shortcuts: [
          {
            text: "本月",
            onClick(picker) {
              picker.$emit("pick", [new Date(), new Date()]);
            },
          },
          {
            text: "今年至今",
            onClick(picker) {
              const end = new Date();
              const start = new Date(new Date().getFullYear(), 0);
              picker.$emit("pick", [start, end]);
            },
          },
          {
            text: "最近六个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              start.setMonth(start.getMonth() - 6);
              picker.$emit("pick", [start, end]);
            },
          },
        ],
      },
      fromData: {
        name: "",
        pageIndex: 1, //当前页码，为第一页
        pageSize: 5, //默认每页最大数为5，可以动态的切换每页最大数
      },
      pageInfo: {
        total: 0, //总数，初始值为0
        pageSizes: [1, 5, 10, 20], //定义每次显示最大的条数
      },
      addDialogVisible: false, //添加用户表单对话框状态，默认为true
      editDialogVisible: false, //修改表单对话框状态，默认为true

      //定义添加员工性别信息选择器
      addEmployeeSexOptions: [
        //性别选择
        {
          gender: "性别1",
          sex: "男",
        },
        {
          gender: "性别2",
          sex: "女",
        },
      ],

      //定义添加员工职位信息选择器
      addEmployeeStateOptions: [
        //职位选择
        {
          stateName: "职位1",
          state: "在职",
        },
        {
          stateName: "职位2",
          state: "实习",
        },
        {
          stateName: "职位3",
          state: "待离职",
        },
      ],

      //定义添加员工部门信息选择器
      addEmployeeDepartOptions: [
        //职位选择
        {
          deptName: "部门1",
          dept: "高管",
        },
        {
          deptName: "部门2",
          dept: "技术部",
        },
        {
          deptName: "部门3",
          dept: "运营部",
        },
        {
          deptName: "部门4",
          dept: "CEO",
        },
        {
          deptName: "部门5",
          dept: "运维部",
        },
      ],

      //定义添加员工学历信息选择器
      addEmployeeDegreeOptions: [
        //职位选择
        {
          degreeName: "学历1",
          degree: "博士后",
        },
        {
          degreeName: "学历2",
          degree: "博士",
        },
        {
          degreeName: "学历3",
          degree: "研究生",
        },
        {
          degreeName: "学历4",
          degree: "本科",
        },
        {
          degreeName: "学历5",
          degree: "大专",
        },
        {
          degreeName: "学历6",
          degree: "其他",
        },
      ],

      //添加员工信息
      addEmployeeInfo: {
        id: "",
        name: "",
        age: "",
        sex: "",
        state: "",
        birthday: "",
        department: "",
        degree: "",
        salary: "",
      },
      //修改员工的信息
      editForm: {
        id: "",
        name: "",
        age: "",
        sex: "",
        state: "",
        birthday: "",
        department: "",
        degree: "",
        salary: "",
      },
      // 表单验证规则
      AddFormRules: {
        name: [
          {
            message: "请输入员工名字",
            required: true,
            validator: validateUsername,
            trigger: "blur",
          },
        ],
        age: [
          {
            message: "请输入年龄",
            required: true,
            validator: validateAge,
            trigger: "blur",
          },
        ],
        sex: [
          {
            message: "请选择性别",
            required: true,
            validator: validatGender,
            trigger: "blur",
          },
        ],
        state: [
          {
            message: "请选择员工当前状态",
            required: true,
            validator: validateState,
            trigger: "blur",
          },
        ],
        birthday: [
          {
            message: "请选择员工生日",
            required: true,
            validator: validateBirthday,
            trigger: "blur",
          },
        ],
        department: [
          {
            message: "请选择员工部门",
            required: true,
            validator: validateDepartment,
            trigger: "blur",
          },
        ],
        degree: [
          {
            message: "请选择员工学历",
            required: true,
            validator: validateDegree,
            trigger: "blur",
          },
        ],
        salary: [
          {
            message: "请输入员工薪水",
            required: true,
            validator: validateSalary,
            trigger: "blur",
          },
        ],
      },
      //表单验证规则
      editFormRules: {
        name: [
          {
            required: true,
            validator: validateUsername,
            trigger: "blur",
          },
        ],
        age: [
          {
            required: true,
            validator: validateAge,
            trigger: "blur",
          },
        ],
        sex: [
          {
            required: true,
            validator: validatGender,
            trigger: "blur",
          },
        ],
        state: [
          {
            required: true,
            validator: validateState,
            trigger: "blur",
          },
        ],
        birthday: [
          {
            required: true,
            validator: validateBirthday,
            trigger: "blur",
          },
        ],
        department: [
          {
            required: true,
            validator: validateDepartment,
            trigger: "blur",
          },
        ],
        degree: [
          {
            required: true,
            required: true,
            validator: validateDegree,
            trigger: "blur",
          },
        ],
        salary: [
          {
            required: true,
            validator: validateSalary,
            trigger: "blur",
          },
        ],
      },
    };
  },
  methods: {
    queryEmpList() {
      var $that = this;
      list(this.fromData).then((res) => {
        if (res.code == 200 && res.success == "success") {
          $that.employeeList = res.data.list;
          $that.pageInfo.total = res.data.total;
        }
      });
    },

    /* 重置表单信息，将数据置空 */
    resetserchForm() {
      this.$message.success("重置表单信息成功"); //显示重置成功的信息
      this.$refs.searchFormRef.resetFields(); //重置对话框数据
    },

    //时间进行格式化输出，格式化为yy-mm-dd
    dateFormat: function (row) {
      const dateStr = row.birthday; //获得当前row的值
      if (dateStr != null) {
        let date = new Date(row.birthday); //实例化一个date对象
        let yy = date.getFullYear();
        let MM = date.getMonth() + 1;
        MM = MM < 10 ? "0" + MM : MM;
        let dd = date.getDate();
        dd = dd < 10 ? "0" + dd : dd;
        return yy + "-" + MM + "-" + dd;
      }
    },

    //修改员工信息显示对话框，根据员工id的值获得修改信息
    async showEditDialog(id) {
      const { data: res } = await this.$http.get(
        "http://localhost:9005/sys/employee/getInfo?id=" + id
      );
      this.editForm = res.data; //查询到的员工信息存放在editform中
      this.editDialogVisible = true; //将对话框设为true
    },

    //修改员工信息方法,已实现--04.20
    doModifyEmployee() {
      this.$refs.editFormRef.validate(async (valid) => {
        if (!valid) return;
        const { data: res } = await this.$http.put(
          "http://localhost:9005/sys/employee/update",
          this.editForm
        );
        if (res.code != 200 && res.success != "success") {
          return this.$message.error("修改失败！！！");
        }
        this.$message.success("修改员工信息成功");
        this.editDialogVisible = false;
        this.queryEmpList(); //重新获得员工列表信息
      });
    },

    //对数据修改后关闭对话框
    editDialogClosed() {
      this.$refs.editFormRef.resetFields(); //重置对框框区域信息
    },

    //模糊查询方法
    searchEmployee() {
      this.queryEmpList();
      this.$message.success("查询成功");
    },

    // //添加用户的方法 --04.21，bug改好！
    doAddEmployee() {
      var $that = this;
      this.$refs.addFormRef.validate(async (valid) => {
        if (!valid) return;
        const { data: res } = await this.$http.post(
          "http://localhost:9005/sys/employee/add", //调用后端api接口
          this.addEmployeeInfo
        );
        if (res.code != 200 && res.success != "success") {
          //通过post请求调用后台addUser的api接口，并把参数存放在addForm里面
          return this.$message.error("添加员工失败"); //如果失败，则返回错误信息
        }
        this.$message.success("添加员工成功");
        this.addDialogVisible = false; //将对话框消失
        this.queryEmpList(); //需要多次调用获取员工列表方法，显示数据
      });
    },

    //监听添加用户的操作，添加完成后退出对话框
    addDialogClosed() {
      this.$refs.addFormRef.resetFields(); //对新增员工对话框进行重置
    },

    //删除员工方法,在删除员工的同时,将数据存放在回收站中,后期可以进行恢复
    handleDelete(id, row) {
      this.$confirm(
        "此操作将删除 " + row.name + " （可在回收站中找回）, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(() => {
          //为了员工信息备份功能 把传入单个参数变成传入多个参数
          var params = {
            id: row.id, //员工id
            name: row.name, //员工姓名
            sex: row.sex, //性别
            birthday: row.birthday, //生日
            modifyTime: row.modifyTime, //修改时间
            department: row.department, //部门
            age: row.age, //年龄
            state: row.state, //员工状态
            salary: row.salary, //薪水
            degree: row.degree, //学历
            status: row.status, //考勤状态
          };
          //先进行回收,其次进行删除
          recycle(params).then();
          del(params).then((res) => {
            if (res.code == 200 && res.success == "success" && res.data >= 1) {
              this.$message({
                type: "success",
                message: "删除" + row.name + "成功!",
              });
              //删除后重新查询即刷新数据
              this.queryEmpList();
            } else {
              this.$message({
                type: "success",
                message: "删除" + row.name + "失败!",
              });
            }
          });
        })
        .catch(() => {
          //点击取消
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },

    //每页显示的条目个数的1改变
    handleSizeChange(val) {
      this.fromData.pageSize = val; //重新对每页显示条数进行更改
      this.queryEmpList(); //重新获得列表的值
    },
    //当前页数的改变
    handleCurrentChange(val) {
      this.fromData.pageIndex = val; //对当前页数进行更改
      this.queryEmpList(); //重新获得员工列表的值
    },
  },
};
</script>

<style Lang="less" scoped>
/* 设置主体布局样式 */
.container {
  font-size: 14px;
  /* 设置文字大小 */
  color: #606266; /* 设置颜色样式 */
  height: 100px;
}

/* el-form表单三个按钮样式，缩小与表单之间的间隔 */
.btn_form {
  height: 100%; /* 设置div的高度 */
  margin: -14px 0px; /* 设置外边距 */
}
</style>
